//microcommand define espeak
const execa = require("execa")
signature("<text:rawtext>", {
  showWarnings: true,
  checkUnknown: true,
})
option("voice", "-v <voicename>")
option("pitch", "-p <0-99:natural>")
option("speed", "-s <80-450:posint>")
option("voices")
example("espeak -v jbo+f2 coi rodo")
before(async ({ session, options: { voices } }) => {
  if (voices) {
    const { stdout } = await execa("espeak", ["--voices"])
    let table =
      session.text(".languages") +
      "\n" +
      stdout
        .trim()
        .split("\n")
        .slice(1)
        .map(l => {
          const [, code, , name] = l.trim().split(/\s+/g)
          return code + " (" + name + ")"
        })
        .join("\n") +
      "\n" +
      session.text(".voices") +
      "\nf1 f2 f3 f4 f5\nm1 m2 m3 m4 m5 m6 m7\nwhisper whisperf"
    return h("execute", "imagify " + table)
  }
})
action(({ session, options: { voice, pitch, speed } }, text) => {
  if (!text.trim()) return session.text(".expect-text")
  const args = ["--stdout"]
  if (voice) args.push("-v", voice)
  if (pitch) args.push("-p", pitch)
  if (speed) args.push("-s", speed)
  return execa("espeak", args, {
    input: text,
    encoding: null,
  }).then(
    ({ stdout }) => h.audio(stdout, "audio/wav"),
    err => h.text(String(err))
  )
})
locale("zh-CN", {
  description: "某种语音合成",
  options: {
    voice: "指定语言和语音（语音可省略，未省略时加号分隔）",
    pitch: "指定声调（默认 50）",
    speed: "指定语速（默认 175）",
    voices: "显示可用语言和语音列表",
  },
  messages: {
    languages: "语言：",
    voices: "语音：",
    "expect-text": "缺少文本…",
  },
})